<template>
  <div class="friends-container">
    <div class="friends-header">
      <h2>我的好友</h2>
      <button @click="showAddFriendDialog = true" class="add-btn">添加好友</button>
    </div>

    <div class="friends-list">
      <div v-for="friend in friends" :key="friend.id" class="friend-item">
        <div class="friend-avatar">{{ friend.avatar || '默' }}</div>
        <div class="friend-info">
          <div class="friend-name">{{ friend.username }}</div>
          <div class="friend-status">{{ friend.isOnline ? '在线' : '离线' }}</div>
        </div>
        <div class="friend-actions">
          <button @click="startChat(friend.id)" class="chat-btn">聊天</button>
          <button @click="deleteFriend(friend.id)" class="delete-btn">删除</button>
        </div>
      </div>
    </div>

    <!-- 添加好友弹窗 -->
    <div v-if="showAddFriendDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h3>添加好友</h3>
        <input
          v-model="searchUsername"
          placeholder="输入用户名搜索"
          class="search-input"
        >
        <button @click="searchUser" class="search-btn">搜索</button>

        <div v-if="searchResult" class="search-result">
          <div class="user-info">
            <div class="user-avatar">{{ searchResult.avatar || '默' }}</div>
            <div class="user-name">{{ searchResult.username }}</div>
          </div>
          <button @click="addFriend(searchResult.id)" class="add-friend-btn">添加</button>
        </div>

        <button @click="showAddFriendDialog = false" class="close-btn">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { friendsApi } from '@/api'
import { useUserStore } from '@/stores/user'

uni.showToast({ title: '进入好友页面', icon: 'none', duration: 1000 })
// 状态管理
const userStore = useUserStore()

// 好友数据
const friends = ref([])
const showAddFriendDialog = ref(false)
const searchUsername = ref('')
const searchResult = ref(null)

// 获取好友列表
const getFriendList = async () => {
  try {
    const res = await friendsApi.getFriendList()
    friends.value = res.data
  } catch (error) {
    console.error('获取好友列表失败:', error)
    uni.showToast({ title: '获取好友列表失败', icon: 'none' })
  }
}

// 搜索用户
const searchUser = async () => {
  if (!searchUsername.value.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' })
    return
  }

  try {
    // 实际项目中需要实现搜索用户的API
    const res = await friendsApi.searchUser(searchUsername.value)
    searchResult.value = res.data
  } catch (error) {
    console.error('搜索用户失败:', error)
    uni.showToast({ title: '搜索用户失败', icon: 'none' })
  }
}

// 添加好友
const addFriend = async (userId) => {
  try {
    await friendsApi.addFriend(userId)
    uni.showToast({ title: '添加好友请求已发送', icon: 'success' })
    showAddFriendDialog.value = false
    searchUsername.value = ''
    searchResult.value = null
    // 刷新好友列表
    getFriendList()
  } catch (error) {
    console.error('添加好友失败:', error)
    uni.showToast({ title: '添加好友失败', icon: 'none' })
  }
}

// 删除好友
const deleteFriend = async (userId) => {
  try {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除这个好友吗？',
      success: async (res) => {
        if (res.confirm) {
          await friendsApi.deleteFriend(userId)
          uni.showToast({ title: '删除好友成功', icon: 'success' })
          // 刷新好友列表
          getFriendList()
        }
      }
    })
  } catch (error) {
    console.error('删除好友失败:', error)
    uni.showToast({ title: '删除好友失败', icon: 'none' })
  }
}

// 开始聊天
const startChat = async (userId) => {
  try {
    // 检查是否已有房间
    const res = await friendsApi.getOrCreateChatRoom(userId)
    uni.setStorageSync('roomId', res.data.roomId)
    uni.navigateTo({ url: '/pages/chat/chat' })
  } catch (error) {
    console.error('创建聊天房间失败:', error)
    uni.showToast({ title: '进入聊天失败', icon: 'none' })
  }
}

// 组件挂载时
onMounted(() => {
  if (!userStore.isLogin) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  getFriendList()
})
</script>

<style scoped>
.friends-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 16px;
}

.friends-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.friends-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.friend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.friend-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  margin-right: 16px;
}

.friend-info {
  flex: 1;
}

.friend-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.friend-status {
  font-size: 14px;
  color: #888888;
}

.friend-actions {
  display: flex;
  gap: 8px;
}

.chat-btn {
  padding: 6px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-btn {
  padding: 6px 12px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.search-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 16px;
}

.search-btn {
  width: 100%;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 16px;
}

.search-result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
}

.add-friend-btn {
  padding: 6px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.close-btn {
  width: 100%;
  padding: 12px;
  background-color: #f5f5f5;
  color: #333333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>